package com.xiyue.server.controller;

import cn.hutool.core.lang.UUID;
import com.sport.common.web.model.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("common")
public class CommonController {
    private final String path = "/uploads/imgs";

    @PostMapping("upload")
    public Result<String> upload(@RequestBody MultipartFile file) {
        if(file.isEmpty()) {
            return Result.error("文件为空,请选择文件进行上传");
        }
            try {
                // 保存文件到本地系统,保存到uploads/imgs目录
                File dir = new File(path);
                if(!dir.exists()) {
                    dir.mkdirs();
                }
                if (file.getOriginalFilename() != null) {
                    String filename = this.filename(file.getOriginalFilename());
                    //使用原始的文件名保存文件
                    String filePath = path + filename;
                    file.transferTo(Paths.get(filePath));
                    return Result.success("文件上传成功!",filename);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return Result.error("文件上传失败");
    }

    /**
     *  在springboot中
     *      把文件流输出到浏览器中,可以通过servletResponse中的ServletOutputStream
     *  完成
     * @param filename
     * @param response
     */
    @SneakyThrows
    @GetMapping("view/{filename}")
    public void getImage(@PathVariable String filename,
                           HttpServletResponse response) {
        String contextType = this.getContextType(filename);
        response.setContentType(contextType);
        try(
                // 使用ServletOutputStream写入图片数据
                ServletOutputStream sot = response.getOutputStream();
                InputStream ins = new BufferedInputStream(new FileInputStream(path + filename))){
            // 如果是视频的情况下，得设置相应长度
            if(contextType.equals("video/mp4")) {
                response.setContentLengthLong(ins.available());
            }
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = ins.read(buffer)) != -1) {
                sot.write(buffer, 0, bytesRead);
            }
        }
    }

    /**
     *  根据文件名生成时间文件名
     * @param filename
     * @return
     */
    public String filename(String filename){
        return UUID.randomUUID() + filename.substring(filename.lastIndexOf(".") + 1);
    }

    private String getContextType(String filename){
        String sufix = filename.substring(filename.lastIndexOf(".") + 1);
        return switch (sufix){
            case "png","PNG" -> MediaType.IMAGE_PNG_VALUE;
            case "jpg","JPG" -> MediaType.IMAGE_JPEG_VALUE;
            case "gif","GIF" -> MediaType.IMAGE_GIF_VALUE;
            case "mp4","MP4" -> "video/mp4";
            default -> MediaType.APPLICATION_JSON_VALUE;
        };
    }
}
